<?php
class Session_Basket_Core {
	public $contents = array();

	public function clear(){
		if (isset($this->contents)){
			foreach ($this->contents as $key => $item){
				unset($this->contents[$key]);
			}
		}
	}

	private function create_key($id){
		return "$id";
	}

	public function add($id, $quantity){

		$key = $this->create_key($id);
		if (isset($this->contents[$key])){
			$this->contents[$key]->add($id, $quantity);
		}
		else {
			$this->contents[$key] = new basket_item($id, $quantity);
		}
	}

	public function remove($key){
		unset($this->contents[$key]);
	}

	public function updateQuantity($key,$aQuantity){
		if (isset($this->contents[$key])){
			$this->contents[$key]->add($key, $aQuantity);
		}
	}


	public function cost(){
		$cost = 0;
		if (isset($this->contents)){
			foreach ($this->contents as $product => $basket_item){
				$cost += $basket_item->cost;
			}
		}
		return $cost;
	}

	public  function get(){
		return Session::instance()->get("basket");
	}

	public  function getOrCreate(){
		$session = Session::instance();

		$basket = $session->get("basket");
		if (!$basket)
		{
			$basket = new Session_Basket();
			$session->set("basket", $basket);
		}
		return $basket;
	}

}


class basket_item {
	public $product_id;
	public $quantity;
	public $cost = 0;
	public $cost_per = 0;

	public function __construct($aProduct_id, $aQuantity){
		// TODO check individual product.
		$this->product_id = $aProduct_id;
		$this->quantity = $aQuantity;
		$this->calculate_cost();
	}

	private function calculate_cost(){
		$prod = ORM::factory("product")->find($this->product_id);
		$this->cost = $prod->price * $this->quantity;
		$this->cost_per = $prod->price;
	}

	public function add($quantity){
		$this->quantity += $quantity;
		$this->calculate_cost();
	}

	public function size(){
		return $this->quantity;
	}

	public function product_description(){
		$prod = ORM::factory("product")->find($this->product_id);
		return $prod->description;
	}

	public function getProduct(){
		$prod = ORM::factory("product")->find($this->product_id);
		return $prod;
	}

	public function getCode(){
		$prod = ORM::factory("product")->find($this->product_id);
		return $photo->id." - ".$prod->name;
	}

}

?>